package com.java.service;

import com.fasterxml.jackson.databind.ObjectMapper;
import com.java.entity.vo.FileUploadResult;
import com.java.entity.vo.WeChatAddMaterialResponse;
import lombok.extern.slf4j.Slf4j;
import org.apache.http.Header;
import org.apache.http.HttpEntity;
import org.apache.http.HttpRequest;
import org.apache.http.HttpStatus;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.mime.MultipartEntityBuilder;
import org.apache.http.entity.mime.content.FileBody;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.util.EntityUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.mock.web.MockMultipartFile;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.URI;
import java.net.URL;
import java.net.URLConnection;
import java.net.URLDecoder;
import java.nio.charset.StandardCharsets;
import java.util.HashMap;
import java.util.Map;

@Slf4j
@Service
public class WeChatMaterialService {
    @Autowired
    private MinioService minioService;

    private static final ObjectMapper OBJECT_MAPPER = new ObjectMapper();

    public WeChatAddMaterialResponse uploadMaterial(String accessToken, String type, String fileUrl) throws Exception {
        // 将fileUrl解析，上传到minio
        String base64Png = minioService.convertImageUrlToBase64Png(fileUrl);
        FileUploadResult fileUploadResult = minioService.uploadBase64Image(base64Png);
        String url = String.format(
                "https://api.weixin.qq.com/cgi-bin/material/add_material?access_token=%s&type=%s",
                accessToken, type
        );
        log.info("上传media的URL: {}", url);

        // 从URL转换为MultipartFile
        MultipartFile multipartFile = convertUrlToMultipartFile(fileUploadResult.getUrl());

        // 临时文件
        File temp = File.createTempFile("wx_mat_", multipartFile.getOriginalFilename());

        try {
            multipartFile.transferTo(temp);

            HttpPost post = new HttpPost(url);
            MultipartEntityBuilder builder = MultipartEntityBuilder.create();
            // 明确设置MIME类型（根据文件扩展名）
            String contentType = multipartFile.getContentType();
            builder.addPart("media", new FileBody(temp, contentType != null ? contentType : "application/octet-stream"));

            HttpEntity entity = builder.build();
            post.setEntity(entity);

            try (CloseableHttpClient client = HttpClients.createDefault();
                 CloseableHttpResponse response = client.execute(post)) {
                String resp = EntityUtils.toString(response.getEntity(), "UTF-8");
                log.info("上传素材返回结果: {}", resp);
                return OBJECT_MAPPER.readValue(resp, WeChatAddMaterialResponse.class);
            }
        } finally {
            if (temp.exists()) {
                temp.delete();
            }
        }
    }

    /**
     * 将URL转换为MockMultipartFile
     */
    private MultipartFile convertUrlToMultipartFile(String fileUrl) throws IOException {
        URL url = new URL(fileUrl);
        // 解析URL参数（获取x-wf-file_name作为文件名）
        Map<String, String> params = parseUrlParams(url);
        String fileName = params.getOrDefault("x-wf-file_name", extractFileNameFromPath(url.getPath()));
        // 解码URL编码的文件名（如%E7%8F%8D%E7%8F%A0转换为中文）
        fileName = URLDecoder.decode(fileName, StandardCharsets.UTF_8.name());

        // 打开连接并设置请求头（避免防盗链）
        URLConnection connection = url.openConnection();
        connection.setConnectTimeout(10000); // 10秒连接超时
        connection.setReadTimeout(10000);    // 10秒读取超时

        // 获取输入流（使用系统默认证书验证）
        try (InputStream inputStream = connection.getInputStream()) {
            // 获取MIME类型（优先从连接获取，否则根据扩展名推测）
            String contentType = connection.getContentType();
            if (contentType == null || contentType.contains("application/octet-stream")) {
                contentType = getMimeTypeByFileName(fileName);
            }

            // 创建MockMultipartFile
            return new MockMultipartFile(
                    "file",       // 参数名
                    fileName,     // 文件名
                    contentType,  // MIME类型
                    inputStream   // 文件流
            );
        } catch (IOException e) {
            log.error("下载URL文件失败: {}", fileUrl, e);
            throw new IOException("无法下载URL文件: " + fileUrl, e);
        }
    }

    /**
     * 解析URL查询参数为Map
     */
    private  Map<String, String> parseUrlParams(URL url) {
        Map<String, String> params = new HashMap<>();
        String query = url.getQuery();
        if (query == null || query.isEmpty()) {
            return params;
        }
        String[] pairs = query.split("&");
        for (String pair : pairs) {
            String[] keyValue = pair.split("=", 2);
            if (keyValue.length == 2) {
                params.put(keyValue[0], keyValue[1]);
            }
        }
        return params;
    }

    /**
     * 从URL路径中提取文件名（作为x-wf-file_name不存在时的 fallback）
     */
    private String extractFileNameFromPath(String path) {
        int lastSlash = path.lastIndexOf('/');
        String fileName = (lastSlash != -1) ? path.substring(lastSlash + 1) : "unknown_file";
        // 移除可能的后缀处理（如~tplv-xxx）
        int tildeIndex = fileName.indexOf('~');
        if (tildeIndex != -1) {
            fileName = fileName.substring(0, tildeIndex);
        }
        return fileName;
    }

    /**
     * 根据文件名推测MIME类型
     */
    private String getMimeTypeByFileName(String fileName) {
        if (fileName.endsWith(".png")) {
            return "image/png";
        } else if (fileName.endsWith(".jpg") || fileName.endsWith(".jpeg")) {
            return "image/jpeg";
        } else if (fileName.endsWith(".gif")) {
            return "image/gif";
        } else if (fileName.endsWith(".mp4")) {
            return "video/mp4";
        } else {
            return "application/octet-stream";
        }
    }
}

// https://p6-official-plugin-sign.byteimg.com/tos-cn-i-5jbd59dj06/4c218dc49ac6490fb4e335b785df2d15~tplv-5jbd59dj06-image.png?lk3s=8c875d0b&x-expires=1783854003&x-signature=qsCkg%2BO5NCoE8dJ7F4OkH6bGwr8%3D